package tvp.ltdd.fake_call_sms.activity;

import tvp.ltdd.fake_call_sms.R;
import tvp.ltdd.fake_call_sms.helper.CallLogHelper;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class Call extends Activity implements OnClickListener {

	private WakeLock fullWakeLock, partialWakeLock;
	private Button btnAnswer, btnDecline;
	private ImageView ivContact;
	private TextView tvName, tvNumber, tvTimer;
	private Vibrator vb;
	private Ringtone r;
	private String name, number, ringTonePath, phoneId;
	private boolean vibrate;
	private int second = 0, minute = 0, duration = 0, wait = 0;
	public Handler mHandler = new Handler();
	public Handler mHandler2 = new Handler();
	private NotificationManager myNotificationManager;
	private int notificationIdOne = 111;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		createWakeLocks();
		wakeDevice();
		setContentView(R.layout.incall);
		Log.v("********", "Chay call activity");

		btnAnswer = (Button) findViewById(R.id.btnAnswer);
		btnDecline = (Button) findViewById(R.id.btnDecline);
		ivContact = (ImageView) findViewById(R.id.ivContact);
		tvName = (TextView) findViewById(R.id.tvName);
		tvNumber = (TextView) findViewById(R.id.tvNumber);
		tvTimer = (TextView) findViewById(R.id.tvTimer);
		tvTimer.setVisibility(View.INVISIBLE);
		Bundle extra = getIntent().getExtras();
		if (extra != null) {
			name = extra.getString("name");
			number = extra.getString("number");
			ringTonePath = extra.getString("ringtonepath");
			phoneId = extra.getString("phoneId");
			vibrate = extra.getBoolean("vibrate");
		}
		tvName.setText(name);
		tvNumber.setText(number);
		if (phoneId != null) {
			Long temp = Long.valueOf(phoneId).longValue();
			ivContact.setImageURI(getPhotoUri(temp));
			Log.v("phoneId", phoneId);
		}

		btnAnswer.setOnClickListener(this);
		btnDecline.setOnClickListener(this);
		if (ringTonePath != null) {
			Uri notification = Uri.parse(ringTonePath);
			Log.v("***********", ringTonePath);
			r = RingtoneManager.getRingtone(getApplicationContext(),
					notification);
			r.play();
		}

		vb = (Vibrator) this.getApplicationContext().getSystemService(
				Context.VIBRATOR_SERVICE);

		mHandler2.post(runnable2);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAnswer:
			Log.v("*********", "Answer the phone");

			r.stop();
			vb.cancel();
			btnAnswer.setVisibility(View.GONE);
			tvTimer.setVisibility(View.VISIBLE);
			mHandler.post(runnable);
			mHandler2.removeCallbacks(runnable2);
			btnDecline.setText("End call");
			break;
		case R.id.btnDecline:
			if (duration == 0) {
				Log.v("***************", "Decline the phone");
				CallLogHelper.insertPlaceholderCall(getContentResolver(),
						tvName.getText().toString(), tvNumber.getText()
								.toString(), 1, 0, System.currentTimeMillis());
				displayNotification();
				r.stop();
				vb.cancel();
				finish();
			} else {
				Log.v("duration", "" + duration);
				CallLogHelper.insertPlaceholderCall(getContentResolver(),
						tvName.getText().toString(), tvNumber.getText()
								.toString(), 2, duration, System
								.currentTimeMillis());
				finish();
			}
			break;
		}
	}

	protected void createWakeLocks() {

		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		fullWakeLock = powerManager
				.newWakeLock(
						(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
								| PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),
						"Loneworker - FULL WAKE LOCK");
		partialWakeLock = powerManager
				.newWakeLock(
						(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
								| PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),
						"Loneworker - FULL WAKE LOCK");
	}

	public void wakeDevice() {
		fullWakeLock.acquire();

		KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
		keyguardLock.disableKeyguard();
	}

	@Override
	protected void onPause() {
		super.onPause();
		partialWakeLock.acquire();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (fullWakeLock.isHeld()) {
			fullWakeLock.release();
		}
		if (partialWakeLock.isHeld()) {
			partialWakeLock.release();
		}

	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			/* do what you need to do */
			tvTimer.setText(pad(minute) + ":" + pad(second));
			Log.v("speak duration", pad(minute) + ":" + pad(second));
			second++;
			duration++;
			if (second == 60) {
				second = 0;
				minute++;
			}
			/* and here comes the "trick" */
			mHandler.postDelayed(this, 1000);
		}
	};

	private Runnable runnable2 = new Runnable() {
		@Override
		public void run() {
			if (vibrate)
				vb.vibrate(1000);
			wait += 2;
			if (wait == 30) {
				CallLogHelper.insertPlaceholderCall(getContentResolver(),
						tvName.getText().toString(), tvNumber.getText()
								.toString(), 1, 0, System.currentTimeMillis());
				displayNotification();
				r.stop();
				vb.cancel();
				finish();
			}
			/* and here comes the "trick" */
			mHandler2.postDelayed(this, 2000);
		}
	};

	public void displayNotification() {
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this);

		mBuilder.setContentTitle("Missed call");
		mBuilder.setContentText(name + " " + number);
		mBuilder.setTicker("Missing call from " + name + " " + number);
		mBuilder.setSmallIcon(R.drawable.stat_notify_missed_call);
		mBuilder.setLights(Color.BLUE, 300, 1000);
		myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		myNotificationManager.notify(notificationIdOne, mBuilder.build());

	}

	public Uri getPhotoUri(long contactId) {
		ContentResolver contentResolver = getContentResolver();

		try {
			Cursor cursor = contentResolver
					.query(ContactsContract.Data.CONTENT_URI,
							null,
							ContactsContract.Data.CONTACT_ID
									+ "="
									+ contactId
									+ " AND "

									+ ContactsContract.Data.MIMETYPE
									+ "='"
									+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
									+ "'", null, null);

			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					return null; // no photo
				}
			} else {
				return null; // error in cursor process
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		Uri person = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		return Uri.withAppendedPath(person,
				ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.exit(0);
	}

}
